<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>角色管理系统</title>
  <!-- 引入Vue2 -->
  <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
  <!-- 引入axios -->
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  <!-- 引入Element UI 样式 -->
  <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
  <!-- 引入Element UI 组件库 -->
  <script src="https://unpkg.com/element-ui/lib/index.js"></script>
  <style>
    .container {
      max-width: 1200px;
      margin: 0 auto;
      padding: 20px;
    }
    .header {
      margin-bottom: 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .role-card {
      margin-bottom: 10px;
      padding: 15px;
      border-radius: 4px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }
    .role-actions {
      float: right;
    }
    .form-container {
      margin-top: 30px;
      padding: 20px;
      border-radius: 4px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }
    .api-table {
      margin-top: 20px;
    }
  </style>
</head>
<body>
<div id="app">
  <div class="container">
    <div class="header">
      <h1>角色管理系统</h1>
      <el-button type="primary" @click="showAddForm" icon="el-icon-plus">新增角色</el-button>
    </div>

    <el-card v-if="roles.length === 0" class="empty-card">
      <div slot="header" class="clearfix">
        <span>暂无角色数据</span>
      </div>
      <div class="text item">
        点击上方"新增角色"按钮添加第一个角色
      </div>
    </el-card>

    <div v-else>
      <el-card v-for="role in roles" :key="role.id" class="role-card">
        <div slot="header" class="clearfix">
          <span><strong>{{ role.name }}</strong> - {{ role.description }}</span>
          <div class="role-actions">
            <el-button size="mini" @click="showUpdateFrom(role.id)" icon="el-icon-edit">编辑</el-button>
          </div>
        </div>
        <div class="text item">
          <el-tag v-for="api in getRoleApis(role.id)" :key="api.id" type="info" style="margin-right: 5px;">
            {{ api.name }}
          </el-tag>
        </div>
      </el-card>
    </div>

    <el-dialog :title="currentRole.id ? '编辑角色' : '新增角色'" :visible.sync="showSaveForm" width="70%">
      <div class="form-container">
        <el-form :model="currentRole" label-width="100px" :rules="rules" ref="roleForm">
          <el-form-item label="角色ID" prop="id" v-if="currentRole.id">
            <el-input v-model="currentRole.id" disabled></el-input>
          </el-form-item>
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="currentRole.name" placeholder="请输入角色名称"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="currentRole.description" placeholder="请输入角色描述"></el-input>
          </el-form-item>

          <el-divider></el-divider>

          <el-form-item label="API权限">
            <el-table :data="allApis" class="api-table" border stripe height="300">
              <el-table-column prop="name" label="API名称" width="180"></el-table-column>
              <el-table-column prop="path" label="API路径"></el-table-column>
              <el-table-column prop="description" label="API描述"></el-table-column>
              <el-table-column label="授权" width="80">
                <template slot-scope="scope">
                  <el-checkbox v-model="currentApiIds" :label="scope.row.id"></el-checkbox>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
      </div>

      <span slot="footer" class="dialog-footer">
                    <el-button @click="showSaveForm = false">取 消</el-button>
                    <el-button type="primary" @click="saveRole">确 定</el-button>
                </span>
    </el-dialog>
  </div>
</div>

<script>
  // 设置axios的默认baseURL
  axios.defaults.baseURL = 'http://localhost:8080';
  // 创建Vue实例
  const app = new Vue({
    el: '#app',
    data: {
      roles: [],
      allApis: [],
      currentRole: {
        id: '',
        name: '',
        description: ''
      },
      currentApiIds: [],
      showSaveForm: false,
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 5, max: 50, message: '长度在 5 到 50 个字符', trigger: 'blur' }
        ]
      }
    },
    created() {
      this.fetchRoles();
      this.fetchAllApis();
    },
    methods: {
      fetchRoles() {
        axios.get('/role/getall')
                .then(response => {
                  if(response.data.success){
                    this.roles = response.data.data;
                  }
                })
                .catch(error => {
                  console.error('获取角色列表失败', error);
                  this.$message.error('获取角色列表失败');
                });
      },
      fetchAllApis() {
        axios.get("/api/getall")
                .then(response => {
                  if(response.data.success){
                    this.allApis = response.data.data;
                  }
                })
                .catch(error => {
                  console.error('获取API列表失败', error);
                  this.$message.error('获取API列表失败');
                });
      },
      getRoleApis(roleId) {
        const role = this.roles.find(r => r.id === roleId);
        if (!role || !role.apiIds) return [];

        return this.allApis.filter(api => role.apiIds.includes(api.id));
      },
      saveRole() {
        this.$refs['roleForm'].validate((valid) => {
          if (valid) {
            const roleSave = {
              id: this.currentRole.id,
              name: this.currentRole.name,
              description: this.currentRole.description,
              apiIds: this.currentApiIds
            };

            const loading = this.$loading({
              lock: true,
              text: '保存中...',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            });

            axios.post('/role/save', roleSave)
                    .then(response => {
                      loading.close();
                      if(response.data.success){
                        this.$message.success('角色保存成功');
                        this.showSaveForm = false;
                        this.fetchRoles();
                      } else {
                        this.$message.error(response.data.message || '保存失败');
                      }
                    })
                    .catch(error => {
                      loading.close();
                      console.error('保存角色失败', error);
                      this.$message.error('保存角色失败');
                    });
          } else {
            this.$message.warning('请填写完整的表单信息');
            return false;
          }
        });
      },
      showUpdateFrom(id) {
        axios.get(`/role/getById/${id}`)
                .then(response => {
                  if(response.data.success){
                    let role = response.data.data;
                    this.currentRole = {
                      id: role.id,
                      name: role.name,
                      description: role.description
                    };
                    this.currentApiIds = role.apiIds || [];
                    this.showSaveForm = true;
                  }
                })
                .catch(error => {
                  console.error('获取角色详情失败', error);
                  this.$message.error('获取角色详情失败');
                });
      },
      showAddForm() {
        this.currentRole = {
          id: '',
          name: '',
          description: ''
        };
        this.currentApiIds = [];
        this.showSaveForm = true;
        this.$nextTick(() => {
          if (this.$refs['roleForm']) {
            this.$refs['roleForm'].clearValidate();
          }
        });
      }
    }
  });
</script>
</body>
</html>